Deployment Status Apache License Documentation Status Python Online Python version—Jan 27, 2021


Copyright © Wei MEI, MLMS™—all rights reserved. 🀤

Date

The datetime module contains a number of classes for manipulating dates and times.

Fast implementation of the datetime type.

class datetime.date[source]

Bases: object

date(year, month, day) –> date object

ctime()

Return ctime() style string.

day
fromisocalendar()

int, int, int -> Construct a date from the ISO year, week number and weekday.

This is the inverse of the date.isocalendar() function

fromisoformat()

str -> Construct a date from the output of date.isoformat()

fromordinal()

int -> date corresponding to a proleptic Gregorian ordinal.

fromtimestamp()

Create a date from a POSIX timestamp.

The timestamp is a number, e.g. created via time.time(), that is interpreted as local time.

isocalendar()

Return a 3-tuple containing ISO year, week number, and weekday.

isoformat()

Return string in ISO 8601 format, YYYY-MM-DD.

isoweekday()

Return the day of the week represented by the date. Monday == 1 … Sunday == 7

max = datetime.date(9999, 12, 31)
min = datetime.date(1, 1, 1)
month
replace()

Return date with new specified fields.

resolution = datetime.timedelta(days=1)
strftime()

format -> strftime() style string.

timetuple()

Return time tuple, compatible with time.localtime().

today()

Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

toordinal()

Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.

weekday()

Return the day of the week represented by the date. Monday == 0 … Sunday == 6

year
class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])[source]

Bases: datetime.date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
fromisoformat()

string -> datetime from datetime.isoformat() output

fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. timespec specifies what components of the time to include (allowed values are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’, and ‘microseconds’).

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
now()

Returns new datetime object representing current time local to tz.

tz
Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

class datetime.time[source]

Bases: object

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) –> a time object

All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

dst()

Return self.tzinfo.dst(self).

fold
fromisoformat()

string -> time from time.isoformat() output

hour
isoformat()

Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].

timespec specifies what components of the time to include.

max = datetime.time(23, 59, 59, 999999)
microsecond
min = datetime.time(0, 0)
minute
replace()

Return time with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
strftime()

format -> strftime() style string.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

utcoffset()

Return self.tzinfo.utcoffset(self).

class datetime.timedelta[source]

Bases: object

Difference between two datetime values.

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.

days

Number of days.

max = datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)
microseconds

Number of microseconds (>= 0 and less than 1 second).

min = datetime.timedelta(days=-999999999)
resolution = datetime.timedelta(microseconds=1)
seconds

Number of seconds (>= 0 and less than 1 day).

total_seconds()

Total seconds in the duration.

class datetime.timezone[source]

Bases: datetime.tzinfo

Fixed offset from UTC implementation of tzinfo.

dst()

Return None.

fromutc()

datetime in UTC -> datetime in local time.

max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
tzname()

If name is specified when timezone is created, returns the name. Otherwise returns offset as ‘UTC(+|-)HH:MM’.

utc = datetime.timezone.utc
utcoffset()

Return fixed offset.

class datetime.tzinfo[source]

Bases: object

Abstract base class for time zone info objects.

dst()

datetime -> DST offset as timedelta positive east of UTC.

fromutc()

datetime in UTC -> datetime in local time.

tzname()

datetime -> string name of time zone.

utcoffset()

datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

Date and time types:

  • date stores year, month, and day
  • time stores hour, minute, and second
  • datetime stores year, month, day, hour, minute, and second
  • timedelta a duration of time between two dates, times, or datetimes

When naming variables follow the PEP-8 Style Guide for Python Code

Converting from string to datetime

Date data types

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#To get current date and time we need to use the datetime library
from datetime import datetime, timedelta
# The now function returns current date and time
today = datetime.now()

print('Today is: ' + str(today))
#You can use timedelta to add or remove days, or weeks to a date
one_day = timedelta(days=1)
yesterday = today - one_day
print('Yesterday was: ' + str(yesterday))

one_week = timedelta(weeks=1)
last_week = today - one_week
print('Last week was: ' + str(last_week))

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#To get current date and time we need to use the datetime library
from datetime import datetime

# The now function returns current date and time
today = datetime.now()

# use day, month, year, hour, minute, second functions
# to display only part of the date
# All these functions return integers
# Convert them to strings before concatenating them to another string
print('Day: ' + str(today.day))
print('Month: ' + str(today.month))
print('Year: ' + str(today.year))

print('Hour: ' + str(today.hour))
print('Minute: ' + str(today.minute))
print('Second: ' + str(today.second))

Demo: dates

1
2
3
4
5
6
7
8
9
#To get current date and time we need to use the datetime library
from datetime import datetime

current_date = datetime.now()
# The now function returns current date and time as a datetime object

# You must convert the datetime object to a string
# before you can concatenate it to another string
print('Today is: ' + str(current_date))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# import the datetime and timedelta modules
from datetime import datetime, timedelta

# When you ask a user for a date tell them the desired date format
birthday = input('When is your birthday (dd/mm/yyyy)? ')

# When you convert the string containing the date into a date object
# you must specify the expected date format
# if the date is not in the expected format Python will raise an exception
birthday_date = datetime.strptime(birthday, '%d/%m/%Y')

print ('Birthday: ' + str(birthday_date))

# Because we converted the string into a date object
# We can use date and time functions such as timedelta with the object
one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday: ' + str(birthday_eve))

PPT Demonstrations

Challenges time

Check the following script and try to find the mistake:

1
2
3
4
# print today's date
# print yesterday's date
# ask a user to enter a date
# print the date one week from the date entered

solutions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from datetime import datetime, timedelta

# print today's date
current_date = datetime.now()
print(current_date)

# print yesterday's date
one_day = timedelta(days=1)
yesterday = current_date - one_day
print('Yesterday was: ' + str(yesterday))

# ask a user to enter a date
date_entered = input('Please enter a date (dd/mm/yyyy): ')
date_entered = datetime.strptime(date_entered, '%d/%m/%Y')

# print the date one week from the date entered
one_week = timedelta(weeks=1)
one_week_later = date_entered + one_week
print('One week later it will be: ' + str(one_week_later))